import { View, Text, ScrollView, DeviceEventEmitter, StyleSheet } from 'react-native';
import FontAwesome from '@expo/vector-icons/FontAwesome';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import MaterialCommunityIcons from '@expo/vector-icons/MaterialCommunityIcons';
import { RootView, Header } from '../../components/Layout';
import ProductServer from '../../common/service/ProductServer';
import CommonServer from '../../common/service/CommonServer';
import * as FORM from "../../components/Form"
import { CStyle, CFlex, CColor } from '../../constant/css'
import { useSetState, useCurrent } from '../../common/hooks/index'
import util from '../../common/utils/util';
import { useEffect } from 'react';
import { ImageBackground } from 'expo-image';

// * 出库/入库 商品
export default function PutAndOut() {
    const routerParams = util.ExpoRouter.useLocalSearchParams()
    console.log('PutAndOut :>> ', JSON.stringify(routerParams))

    const [state, setState] = useSetState({
        product: {},
        form: {
            total: '1',
            price: 0,
            sum: 0,
            postage: 0,
            orderDate: new Date(),
        },
        isLoading: false,
    })

    const [ref, setRef] = useCurrent({
        type: undefined,
    })

    useEffect(() => {
        const { data, type } = routerParams || {}
        const [err, _ = {}] = util.toJson(data)
        state.form.price = _.buyPrice || 0
        setState({ product: _ })
        setRef({ type: parseInt(type) })
    }, [])

    useEffect(() => {
        const { price, total } = state.form
        let val = ''
        if (price && total) {
            val = (price * total).toFixed(2)
        }
        setForm({ sum: val })
    }, [state.form.price, state.form.total])

    const setForm = (obj = {}) => {
        const { form } = state
        const _ = { ...form, ...obj }
        setState({ form: _ })
    }

    const validForm = (obj) => {
        const validConfig = {
            price: (val) => val ? '' : '请输入价格~',
            total: (val) => val ? '' : '请填输入数量~',
            sum: (val) => val ? '' : '请输入总额~',
            orderDate: (val) => val ? '' : '请选择时间~',
        }
        for (const key in validConfig) {
            result = validConfig[key](obj[key])
            if (result) {
                util.showInfo(result)
                return true
            }
        }
        return
    }

    const submitForm = async () => {
        const { isLoading, form, product } = state
        if (form.total > product.total) {
            return util.showInfo('超过最大库存~')
        }
        if (isLoading) return
        setState({ isLoading: true })
        if (validForm(state.form)) {
            return setState({ isLoading: false })
        }
        const params = {
            type: ref.type,
            pId: product.pId,
            price: form.price,
            total: parseInt(form.total),
            sum: form.sum,
            postage: form.postage,
            orderDate: form.orderDate,
        };
        const [err, res] = await ProductServer.saveStockRecord(params);
        if (err) {
            setState({ isLoading: false })
            return util.showInfo(err)
        }
        util.showSuccess('提交成功~')
        util.ExpoRouter.router.back()
        DeviceEventEmitter.emit('refreshProduct')
    }

    const renderHeader = () =>
        <Header
            title={ref.type === 0 ? '商品入库' : '商品出库'}
        />

    const renderForm = () => {
        const isOut = ref.type === 1
        const data = [
            {
                key: 'price',
                type: FORM.FORM_TYPE.INPUT,
                title: isOut ? '售价' : '进价',
                required: true,
                textAlign: 'right',
                onClick: (val) => setForm({ price: val })
            },
            {
                key: 'total',
                type: FORM.FORM_TYPE.INPUT,
                title: '数量',
                required: true,
                textAlign: 'right',
                unit: () => <MaterialIcons name="inventory" size={15} color={CColor.Blue} />,
                keyboardType: 'number-pad',
                onClick: (val) => setForm({ total: val })
            },
            {
                key: 'sum',
                type: FORM.FORM_TYPE.INPUT,
                title: isOut ? '售价总额' : '进价总额',
                required: true,
                textAlign: 'right',
                unit: () => <FontAwesome name="rmb" size={15} color={CColor.Red} />,
                keyboardType: 'numeric',
                onClick: (val) => setForm({ sum: val })
            },
            {
                key: 'postage',
                type: FORM.FORM_TYPE.INPUT,
                title: '邮费',
                required: false,
                textAlign: 'right',
                unit: () => <FontAwesome name="rmb" size={15} color={CColor.Red} />,
                keyboardType: 'numeric',
                onClick: (val) => setForm({ postage: val })
            },
            {
                key: 'orderDate',
                type: FORM.FORM_TYPE.DATE,
                title: isOut ? '销售时间' : '进货时间',
                required: true,
                onClick: (val) => setForm({ orderDate: val })
            },
        ]
        return (
            <FORM.FormList
                data={state.form}
                list={data}
            />
        )
    }

    const renderProduct = () => {
        const { product: _ } = state
        return (
            <View style={styles.productContainer}>
                <View style={[CFlex.row, CFlex.sc, { marginBottom: 10 }]}>
                    <View style={[CStyle.tag, { marginRight: 5 }]}>
                        <Text style={{ color: CColor.White, fontSize: 12 }}>{_.pIp}</Text>
                    </View>
                    <Text numberOfLines={1} style={styles.productName}>{_.name}</Text>
                </View>
                <View style={[CFlex.row, CFlex.ss]}>
                    <FORM.ExpoImage contentFit='contain' style={styles.productBG} source={{ uri: _.cover }} />
                    <View style={{ flex: 1 }}>
                        <View style={[CFlex.row, CFlex.sc]}>
                            <View style={[CStyle.tag, { backgroundColor: CColor.Origin, marginRight: 10 }]}>
                                <Text style={{ color: CColor.White, fontSize: 11 }}>{_.sourceDesc}</Text>
                            </View>
                            <View style={[CStyle.tag, { backgroundColor: CColor.Header }]}>
                                <Text style={{ color: CColor.White, fontSize: 11 }}>{_.statusDesc}</Text>
                            </View>
                        </View>
                        <View style={{ marginTop: 5 }}>
                            <Text style={{ fontSize: 14 }}>
                                <Text style={{ color: CColor.Red, fontWeight: 'blod' }}>{_.boxPrice}￥</Text> {_.categoryDesc}
                            </Text>
                        </View>
                        <View style={{ marginTop: 5 }}>
                            <Text style={{ fontSize: 12 }}>{util.dayjs(_.enterDate).format('YYYY-MM-DD HH:mm')}</Text>
                        </View>
                        <View style={[CFlex.row, CFlex.ec, { marginTop: 5 }]}>
                            <Text style={{ fontSize: 14, color: CColor.Red, fontWeight: 'bold' }}>{_.buyPrice}￥/ {_.sellPrice}￥</Text>
                        </View>
                    </View>
                </View>
            </View>
        )
    }

    return (
        <RootView bg={CColor.White}>
            {renderHeader()}
            <ScrollView showsVerticalScrollIndicator={false}>
                {renderProduct()}
                {renderForm()}
                <View style={{ height: 50 }} />
                <FORM.Button isLoading={state.isLoading} label={'确 认'} onClick={submitForm} />
            </ScrollView>
        </RootView>
    );
}

const styles = StyleSheet.create({
    productContainer: {
        padding: 12, marginHorizontal: 10,
        borderRadius: 5, borderWidth: 1,
    },
    productName: {
        flex: 1, color: CColor.Black, fontWeight: 'bold', fontSize: 15
    },
    productBG: {
        height: 90, width: 120, borderRadius: 5, marginRight: 10,
        borderWidth: 1, borderColor: 'rgba(0,0,0,0.2)',
    },
})
